package com.ruoyi.project.thirdservice.service.baiduyun.ocr;

import com.alibaba.fastjson.JSON;
import com.baidu.aip.ocr.AipOcr;
import com.ruoyi.common.utils.file.ImageUtils;
import com.ruoyi.project.thirdservice.service.baiduyun.entity.ocr.BaiduOcrGeneralReceiptResp;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author yan
 */
@Service
public class BaiduOcrGeneralReceiptServcie {

    private static Logger logger = LoggerFactory.getLogger(BaiduOcrGeneralReceiptServcie.class);

    /**
     * 百度密钥配置信息
     */
    @Value("${baiduyun.ocr.appId}")
    private String APP_ID;

    @Value("${baiduyun.ocr.apiKey}")
    private String API_KEY;

    @Value("${baiduyun.ocr.secretKey}")
    private String SECRET_KEY;

    private static AipOcr OCR_INSTANCE;

    @PostConstruct
    public void setup() {
        OCR_INSTANCE = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
        logger.info(">>> BaiduYun ocr instance setup success!!");
    }

    /**
     * 基于path的票据识别（不推荐）
     *
     * @param path
     * @return
     */
    @Deprecated
    public BaiduOcrGeneralReceiptResp getReceiptWords(String path) {
        HashMap<String, String> options = new HashMap<>(16);

        JSONObject jsonObject = OCR_INSTANCE.receipt(path, options);
        logger.warn(">>> Get Receipt Words with path ==> {}", jsonObject.toString());

        return JSON.parseObject(jsonObject.toString(), BaiduOcrGeneralReceiptResp.class);
    }

    /**
     * 基于bytes的票据识别
     *
     * @param bytes
     * @return
     */
    public BaiduOcrGeneralReceiptResp getReceiptWords(byte[] bytes) {
        HashMap<String, String> options = new HashMap<>(16);

        JSONObject jsonObject = OCR_INSTANCE.receipt(ImageUtils.
                compress(bytes, 512), options);
        logger.warn(">>> Get Receipt Words with path ==> {}", jsonObject.toString());

        return JSON.parseObject(jsonObject.toString(), BaiduOcrGeneralReceiptResp.class);
    }

    private void buildOptions(HashMap<String, String> options) {
        // 是否定位单字符位置，big：不定位单字符位置，默认值；small：定位单字符位置
        options.put("recognize_granularity", "");
        // 是否返回识别结果中每一行的置信度
        options.put("probability", "");
        // normal 使用快速服务;缺省或其它值使用高精度服务
        options.put("accuracy", "");
        // 是否检测图像朝向，默认不检测，即：false。可选值包括true - 检测朝向；false - 不检测朝向。朝向是指输入图像是正常方向、逆时针旋转90/180/270度。
        options.put("detect_direction", "");
    }


    @PostConstruct
    public void test() throws IOException {
        /*
            String path = "/Users/yan/Downloads/timg.jpeg";
            byte[] bytes = FileUtils.readFileToByteArray(new File(path));
            this.getReceiptWords(ImageUtils.compress(bytes, 512));
         */
    }

}
